/*
 * @Description: 
 * @Date: 2023-03-30 22:54:43
 * @LastEditTime: 2023-04-11 22:26:21
 * @Author: Black
 * @FilePath: \store_admin\src\composables\useTabList.js
 */
import { ref } from 'vue'
import { useRoute, onBeforeRouteUpdate } from 'vue-router'
import { useCookies } from "@vueuse/integrations/useCookies"
import { router } from '~/router'

export function useTabList() {
  
  const route = useRoute()
  const cookie = useCookies()

  const activeTab = ref(route.path)
  const tabList = ref([
    {
      title: '后台首页',
      path: "/"
    },
  ])

  // 添加标签导航
  function addTab(tab) {
    let hastab = tabList.value.findIndex(t => t.path == tab.path) == -1
    // console.log(hastab) // 已存在tab返回1 未存在返回-1
    if (hastab) {
      tabList.value.push(tab)
    }
    cookie.set("tabList", tabList.value)
  }

  // 初始化标签导航列表
  function initTabList() {
    let tabs = cookie.get("tabList")
    if (tabs) {
      tabList.value = tabs
    }
  }
  initTabList()

  onBeforeRouteUpdate((to, form) => {
    activeTab.value = to.path
    addTab({
      title: to.meta.title,
      path: to.path
    })
  })

  const changeTab = (t) => {
    // 该事件函数获取的是一个tab的path用t代替
    activeTab.value = t
    // 页面跳转
    router.push(t)
  }

  const removeTab = (t) => {
    let tabs = tabList.value
    let a = activeTab.value
    if (a == t) {
      tabs.forEach((tab, index) => {
        if (tab.path == t) {
          const nextTab = tabs[index + 1] || tabs[index - 1]
          if (nextTab) {
            a = nextTab.path
          }
        }
      })
    }
    activeTab.value = a
    tabList.value = tabList.value.filter(tab => tab.path != t)
    cookie.set("tabList", tabList.value)
  }

  const handleCloseTabs = (c) => {
    // 获取到的是关闭tab的dropdown下拉菜单选项
    if (c == "clearAll") {
      // 切换tab的active状态
      activeTab.value = "/"
      tabList.value = [{
        title: '后台首页',
        path: "/"
      }]
    } else if (c == "clearOther") {
      // 过滤除当前tab和首页tab之外的tab
      tabList.value = tabList.value.filter(tab =>
        tab.path == "/" || tab.path == activeTab.value
      )
    }
    cookie.set("tabList", tabList.value)
  }

  return {
    activeTab,
    tabList,
    changeTab,
    removeTab,
    handleCloseTabs
  }
}